package com.sec.bnjey.global;

import java.io.IOException;

import android.app.Application;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.res.Configuration;

import com.sec.bnjey.bluetooth.BtService;
import com.sec.bnjey.database.DiagDbAdapter;
import com.sec.bnjey.database.DtcDbAdapter;
import com.sec.bnjey.utils.RbLog;

public class GlobalApplication extends Application {
	private static final String TAG = "IKApplication";

	private static Context mAppContext;

	private static BtService mBtService = null;

	private static boolean mDtcFound = false;
	private static boolean mBtOldStatus = false;

	public static Context getAppContext() {
		return mAppContext;
	}

	public static boolean isDtcFound() {
		return mDtcFound;
	}

	public static void setDtcFound(boolean isFound) {
		mDtcFound = isFound;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		RbLog.d(TAG, "onCreate");
		mAppContext = getApplicationContext();
		mBtService = BtService.getBtService();
		DiagDbAdapter.getInstance(GlobalApplication.getAppContext()).open();
	}

	public static BtService getBtService() {
		if (mBtService == null) {
			mBtService = BtService.getBtService();
		}
		return mBtService;
	}


	public static void stopBluetoothService() {
		if (mBtService != null)
			mBtService.stop();
	}


	@Override
	public void onTerminate() {
		DiagDbAdapter.getInstance(GlobalApplication.getAppContext()).close();
		DtcDbAdapter.getInstance(GlobalApplication.getAppContext()).close();
		RbLog.d(TAG, "Application onTerminate.");
		// stopBluetoothService2();
		stopBluetoothService();
		BluetoothSocket bt_soc = BtService.getSocket();

		try {
			bt_soc.getInputStream().close();
			bt_soc.getOutputStream().close();
			bt_soc.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onTerminate();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onLowMemory() {
		RbLog.d(TAG, "Application onLowMemory.");
		super.onLowMemory();
	}

	public static void setBluetoothOldStatus(boolean btOldStatus) {
		mBtOldStatus = btOldStatus;
		RbLog.d(TAG, "setBluetoothOldStatus " + mBtOldStatus);
	}

	public static boolean getBluetoothOldStatus() {

		RbLog.d(TAG, "getBluetoothOldStatus " + mBtOldStatus);
		return mBtOldStatus;
	}

}
